import http from 'http';
import express, { Application } from 'express';
import dotenv from 'dotenv';
import WebSocket from 'ws';

import corsMiddleware from './middleware/cors.middleware';
import routes from './routes/index';
import errorMiddleware from './middleware/error.middleware';
import notFoundMiddleware from './middleware/notfound.middleware';

import verifyClient from './websocket/verify';
import setupWebSocketServer from './websocket';

dotenv.config();
const app: Application = express();

app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static('uploads'));
app.use(express.json());
app.use(corsMiddleware);
app.use('/api', routes);
app.use(notFoundMiddleware);
app.use(errorMiddleware);


const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/ws', verifyClient });

setupWebSocketServer(wss);

server.listen(process.env.APP_PORT, () => {
  console.log(`Server is running on http://localhost:${process.env.APP_PORT}/api`);
  console.log(`WebSocket server is running on ws://localhost:${process.env.APP_PORT}/ws`);
});